package LeetCode._01_树;

import java.util.*;

public class _113_路径总和2 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    List<List<Integer>> res = new LinkedList<>(); //返回结果
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
       if(root == null) return res;
       traver(root,targetSum,new LinkedList<>());
       return res;
    }

    //遍历二叉树
    private void traver(TreeNode root,int target,LinkedList<Integer> path){
        if(root == null) return;

        int result = target - root.val;
        if(root.left == null && root.right == null){
            if(result == 0){ //找到一条相等的路径
                path.addLast(root.val);
                res.add(new LinkedList<>(path));
                path.removeLast();
            }
            return; //直接返回
        }

        //递归遍历左子树，相当于左链表
        path.addLast(root.val);
        traver(root.left,result,path);
        path.removeLast();

        path.addLast(root.val);
        traver(root.right,result,path);
        path.removeLast();
    }

}
